package cn.edu.xmut.chen.zhlg.zhlg.message.controller;


import cn.edu.xmut.chen.zhlg.common.HttpResult.Result;
import cn.edu.xmut.chen.zhlg.zhlg.message.config.MessageConfirmation;
import cn.edu.xmut.chen.zhlg.zhlg.message.config.MessageError;
import cn.edu.xmut.chen.zhlg.zhlg.message.param.MessageQueryParam;
import cn.edu.xmut.chen.zhlg.zhlg.message.param.MessageSendParam;
import cn.edu.xmut.chen.zhlg.zhlg.message.result.ChatResult;
import cn.edu.xmut.chen.zhlg.zhlg.message.result.MessageResult;
import cn.edu.xmut.chen.zhlg.zhlg.message.service.ChatService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "私聊接口")
@ApiSupport(author = "开发团队", order = 1)
@CrossOrigin
public class ChatController {
    private final ChatService chatService;
    private final SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/chat")
    @ApiOperation(value = "发送私聊消息(WebSocket)")
    @ApiOperationSupport(order = 1)
    public void handlePrivateMessage(
            @Payload MessageSendParam param,
            SimpMessageHeaderAccessor headerAccessor) {

        try {
            String senderId = param.getSenderId();
            String receiverId = param.getReceiverId();
            String chatId = param.getChatId();
            String content = param.getContent();
            Integer contentType = param.getContentType();

            log.info("【消息发送】开始处理消息，发送者: {}, 接收者: {}, 聊天室ID: {}",
                    senderId, receiverId, chatId);

            // 参数校验
            if (senderId == null || receiverId == null) {
                log.error("【消息发送】参数错误，senderId 或 receiverId 为空");
                throw new IllegalArgumentException("发送者和接收者ID不能为空");
            }

            // 保存消息到数据库
            MessageResult message = chatService.sendMessage(param);

            String destination = "/topic/chat/" + chatId;
            messagingTemplate.convertAndSend(destination, message);


        } catch (Exception e) {
            log.error("【消息发送】处理失败，发送者: {}, 错误: {}",
                    param != null ? param.getSenderId() : "未知", e.getMessage(), e);

            // 发送错误通知给发送者
            if(param != null && param.getSenderId() != null) {
                messagingTemplate.convertAndSendToUser(
                        param.getSenderId(),
                        "/queue/error",
                        new MessageError("消息发送失败: " + e.getMessage()));
            }
        }
    }

    @GetMapping("/messages")
    @ApiOperation(value = "获取历史消息")
    public List<MessageResult> getMessages(
            @ApiParam(value = "查询参数", required = true)
            MessageQueryParam param) {

        return chatService.getMessages(param);
    }

    @DeleteMapping("/deleteChat")
    @ApiOperation(value = "删除聊天记录")
    public Result deleteChat(
            @ApiParam(value = "删除参数", required = true)
            @RequestBody MessageQueryParam param){
        return chatService.deleteChat(param);
    }

    @GetMapping("/list")
    @ApiOperation("获取消息列表(分页)")
    public Result getMessageList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam String userId) {

        List<ChatResult> result = chatService.getMessageList(userId, pageNum, pageSize);
        return Result.success(result);
    }

}